package com.trex.modules.tbl.service;

import java.sql.SQLException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.trex.modules.tbl.entity.ServerTrexConfig;
import com.trex.modules.tbl.lineform.entity.TblXdZxxdctzd;
import com.trex.modules.tbl.replyform.dao.TblXdJxchsdDao;
import com.trex.modules.tbl.replyform.entity.TblXdJxchsd;
import com.trex.modules.tbl.replyform.service.TblXdJxchsdService;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.jeesite.common.entity.Page;
import com.jeesite.common.service.CrudService;
import com.trex.modules.tbl.entity.TblXdLjzyjl;
import com.trex.modules.tbl.dao.TblXdLjzyjlDao;

import static com.trex.modules.utils.JsonGeneratorDetail.createJson;
import static com.trex.modules.utils.JsonSenderUtil.sendJsonWithHttpClient;

/**
 * 列检作业记录Service
 * @author jy
 * @version 2022-08-29
 */
@Service
public class TblXdLjzyjlService extends CrudService<TblXdLjzyjlDao, TblXdLjzyjl> {
	@Autowired
	private TblXdLjzyjlDao tblXdLjzyjlDao;
	@Autowired
	private TblXdJxchsdService tblXdJxchsdService;
	@Autowired
	private TblXdJxchsdDao tblXdJxchsdDao;

	private final ServerTrexConfig serverTrexConfig;


    public TblXdLjzyjlService(ServerTrexConfig serverTrexConfig) {
        this.serverTrexConfig = serverTrexConfig;
    }

    /**
	 * 获取单条数据
	 * @param tblXdLjzyjl
	 * @return
	 */
	@Override
	public TblXdLjzyjl get(TblXdLjzyjl tblXdLjzyjl) {
		return super.get(tblXdLjzyjl);
	}
	
	/**
	 * 查询分页数据
	 * @param tblXdLjzyjl 查询条件
	 * @param tblXdLjzyjl.page 分页对象
	 * @return
	 */
	@Override
	public Page<TblXdLjzyjl> findPage(TblXdLjzyjl tblXdLjzyjl) {
		return super.findPage(tblXdLjzyjl);
	}


	/**
	 * 查询列表数据
	 * @param tblXdLjzyjl
	 * @return
	 */
	@Override
	public List<TblXdLjzyjl> findList(TblXdLjzyjl tblXdLjzyjl) {
		if (tblXdLjzyjl.getRemarks()!=null){
			tblXdLjzyjl.setRemarks(null);
			return tblXdLjzyjlDao.findListLog(tblXdLjzyjl);
		}
		return tblXdLjzyjlDao.findList(tblXdLjzyjl);
	}
	
	/**
	 * 保存数据（插入或更新）
	 * @param tblXdLjzyjl
	 */
	@Override
	@Transactional
	public void save(TblXdLjzyjl tblXdLjzyjl) {
		super.save(tblXdLjzyjl);
	}
	
	/**
	 * 更新状态
	 * @param tblXdLjzyjl
	 */
	@Override
	@Transactional
	public void updateStatus(TblXdLjzyjl tblXdLjzyjl) {
		super.updateStatus(tblXdLjzyjl);
	}
	
	/**
	 * 删除数据
	 * @param tblXdLjzyjl
	 */
	@Override
	@Transactional
	public void delete(TblXdLjzyjl tblXdLjzyjl) {
		super.delete(tblXdLjzyjl);
	}
	
	/**
               * 更新检车人
	 * @param map 
     */
	@Transactional
    public Map<String, Object> updateJCR(Map<String, Object> map) throws SQLException{
    	tblXdLjzyjlDao.updateJCR(map);
    	return map;
    }
    
    /**
	     * 更新检车人
	* @param map 
	*/
	@Transactional
	public Map<String, Object> updateJCROver(Map<String, Object> map) throws SQLException{
		tblXdLjzyjlDao.updateJCROver(map);
		return map;
	}
	
	/**
	    * 取消
	* @param map  
	*/
	@Transactional
	public Map<String, Object> cancel(Map<String, Object> map) throws SQLException{
		tblXdLjzyjlDao.cancel(map);
		return map;
	}
	
	/**
	    * 取消
	* @param bodyMap
	*/
	public List<TblXdLjzyjl> getLineListByStation(String stationCode,String userCode){
		return tblXdLjzyjlDao.getLineListByStation(stationCode,userCode);
	}
	public List<TblXdLjzyjl> getLineListByStation1(String stationCode,String userCode){
		return tblXdLjzyjlDao.getLineListByStation1(stationCode,userCode);
	}

	public void receiveData(JSONObject json) throws Exception {
		// 创建 ObjectMapper 对象
		ObjectMapper objectMapper = new ObjectMapper();


		JsonNode rootNode = objectMapper.readTree(json.toString());

		// 解析 BODY 并放入 Map 中
		JsonNode bodyNode = rootNode.path("Tables").path("BODY").get(0); // 假设 BODY 只有一个对象
		Map<String, String> bodyMap = new HashMap<>();
		bodyMap.put("OPERATION_FLAG", bodyNode.path("OPERATION_FLAG").asText());
		bodyMap.put("FLAG", bodyNode.path("FLAG").asText());
		bodyMap.put("LINE_CODE", bodyNode.path("LINE_CODE").asText());
		bodyMap.put("LINE", bodyNode.path("LINE").asText());
		bodyMap.put("TIPPER_LINE_CODE", bodyNode.path("TIPPER_LINE_CODE").asText());
		bodyMap.put("WAGON_NUM", bodyNode.path("WAGON_NUM").asText());
		bodyMap.put("SHIFT", bodyNode.path("SHIFT").asText());
		bodyMap.put("TEAM", bodyNode.path("TEAM").asText());
		bodyMap.put("STATION_USER_CODE", bodyNode.path("STATION_USER_CODE").asText());
		bodyMap.put("STATION_USER_NAME", bodyNode.path("STATION_USER_NAME").asText());
		bodyMap.put("STATION_TIME", bodyNode.path("STATION_TIME").asText());
		bodyMap.put("CHECK_FLAG", bodyNode.path("CHECK_FLAG").asText());

		// 解析 DETAIL 并放入 List<Map<String, String>> 中
		JsonNode detailArray = rootNode.path("Tables").path("DETAIL");
		List<Map<String, String>> detailList = new ArrayList<>();
		for (JsonNode detailNode : detailArray) {
			Map<String, String> detailMap = new HashMap<>();
			detailMap.put("REC_ID", detailNode.path("REC_ID").asText());
			detailMap.put("WAGONNO", detailNode.path("WAGONNO").asText());
			detailMap.put("APPLICATION_NUMBER", detailNode.path("APPLICATION_NUMBER").asText());
			detailMap.put("WAGON_TYPE_CODE", detailNode.path("WAGON_TYPE_CODE").asText());
			detailMap.put("WAGON_TYPE_NAME", detailNode.path("WAGON_TYPE_NAME").asText());
			detailMap.put("WAGON_GROUP_CODE", detailNode.path("WAGON_GROUP_CODE").asText());
			detailMap.put("WAGON_GROUP_NAME", detailNode.path("WAGON_GROUP_NAME").asText());
			detailMap.put("STATION_CODE", detailNode.path("STATION_CODE").asText());
			detailMap.put("STATION", detailNode.path("STATION").asText());
			detailMap.put("AREA_CODE", detailNode.path("AREA_CODE").asText());
			detailMap.put("AREA", detailNode.path("AREA").asText());
			detailMap.put("YARDNO_CODE", detailNode.path("YARDNO_CODE").asText());
			detailMap.put("YARDNO", detailNode.path("YARDNO").asText());
			detailMap.put("LINE_CODE", detailNode.path("LINE_CODE").asText());
			detailMap.put("LINE", detailNode.path("LINE").asText());
			detailMap.put("SEND_STATION_CODE", detailNode.path("SEND_STATION_CODE").asText());
			detailMap.put("SEND_STATION", detailNode.path("SEND_STATION").asText());
			detailMap.put("ARRIVE_STATION_CODE", detailNode.path("ARRIVE_STATION_CODE").asText());
			detailMap.put("ARRIVE_STATION", detailNode.path("ARRIVE_STATION").asText());
			detailMap.put("FOCUSAREA", detailNode.path("FOCUSAREA").asText());
			detailMap.put("GOODS_NAME", detailNode.path("GOODS_NAME").asText());
			detailMap.put("IS_NOPEAK", detailNode.path("IS_NOPEAK").asText());
			detailMap.put("SEQ",detailNode.path("SEQ").asText());
			detailList.add(detailMap);
		}

		String CHECK_FLAG = bodyMap.get("CHECK_FLAG").toString();
		int j =  tblXdLjzyjlDao.selectCheck(CHECK_FLAG);
		if (j ==0){
		String typeCode = bodyMap.get("FLAG").toString();

		String shift = bodyMap.get("SHIFT").toString();
		if ("白班".equals(shift)) {
			shift = "2";
		} else {
			shift = "1";
		}
		String uuid = UUID.randomUUID().toString().replace("-", "");
		String lineCode = bodyMap.get("LINE_CODE").toString();
		String line = bodyMap.get("LINE").toString();
		String STATION_USERCODE = bodyMap.get("STATION_USER_CODE").toString();
		String STATION_USERNAME = bodyMap.get("STATION_USER_NAME").toString();
		String STATION_TIME = bodyMap.get("STATION_TIME").toString();
		String team = bodyMap.get("TEAM").toString();
			// 定义日期格式
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");

		// 解析字符串为 java.util.Date
		java.util.Date parsedDate = dateFormat.parse(STATION_TIME);

		// 转换为 java.sql.Timestamp
		Timestamp timestampwww = new Timestamp(parsedDate.getTime());
		tblXdLjzyjlDao.receiveData(uuid,
				typeCode,
				Integer.parseInt(bodyMap.put("WAGON_NUM", bodyNode.path("WAGON_NUM").asText())),
				bodyMap.get("LINE_CODE").toString(),
				line,
				shift,
				team,
				bodyMap.get("STATION_USER_CODE").toString(),
				bodyMap.get("STATION_USER_NAME").toString(),
				timestampwww.toString(),
				CHECK_FLAG
			);

		for (Map<String, String> detail : detailList) {

			tblXdJxchsdService.receiveData(
					detail.get("REC_ID"),
					uuid,
					detail.get("WAGONNO").toString(),
					detail.get("WAGON_TYPE_CODE").toString(),
					detail.get("WAGON_TYPE_NAME").toString(),
					detail.get("WAGON_GROUP_CODE").toString(),
					detail.get("WAGON_GROUP_NAME").toString(),
					detail.get("STATION_CODE").toString(),
					detail.get("STATION").toString(),
					timestampwww.toString(),
					detail.get("AREA_CODE").toString(),
					detail.get("AREA").toString(),
					detail.get("YARDNO_CODE").toString(),
					detail.get("YARDNO").toString(),
					detail.get("LINE_CODE").toString(),
					detail.get("LINE").toString(),
					detail.get("SEND_STATION_CODE").toString(),
					detail.get("SEND_STATION").toString(),
					detail.get("ARRIVE_STATION_CODE").toString(),
					detail.get("ARRIVE_STATION").toString(),
					detail.get("FOCUSAREA").toString(),
					detail.get("GOODS_NAME").toString(),
					detail.get("IS_NOPEAK").toString(),
                    Integer.parseInt(detail.get("SEQ")));
		}

		long timestamp1 = System.currentTimeMillis();
		// 将时间戳转换为 Date 对象
		Date date = new Date(timestamp1);

		// 使用 SimpleDateFormat 格式化时间戳为 yyyyMMddHHmmss 格式的字符串
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		String formattedDate = sdf.format(date);
		String timestampWithLast4Millis1 = timestamp1 + String.format("%04d", timestamp1 % 10000);
		// SysInfo 数据
		Map<String, Object> sysInfo1 = Map.of(
				"Flag", 0,
				"Msg", "",
				"SvcName", "NEM232",
				"Sender", "NE",
				"UUID", timestampWithLast4Millis1
		);

		// BODY 表的 Columns 数据
		List<Map<String, String>> bodyColumns1 = List.of(
				Map.of("Name", "OPERATE_FLAG", "DataType", "S", "Caption", "操作标志"),
				Map.of("Name", "STATUS", "DataType", "S", "Caption", "标识"),
				Map.of("Name", "OPERATION_TIME", "DataType", "S", "Caption", "操作时间"),
				Map.of("Name", "STATION_TRACK", "DataType", "S", "Caption", "股道号"),
				Map.of("Name", "OPERATOR_NO", "DataType", "S", "Caption", "操作人编号"),
				Map.of("Name", "OPERATOR", "DataType", "S", "Caption", "操作人名称"),
				Map.of("Name", "WAGON_NUM", "DataType", "S", "Caption", "车数")
		);

		// BODY 表的 Rows 数据 操作标记I是开始 E是结束  标识 1是列检 2是动检
		List<List<Object>> bodyRows1 = List.of(
				List.of("I", 1, line, bodyMap.get("STATION_USER_CODE").toString(), bodyMap.get("STATION_USER_NAME").toString(), 0)
		);

		// DETAIL 表的 Columns 数据
		List<Map<String, String>> detailColumns = List.of(
				Map.of("Name", "REC_ID", "DataType", "S", "Caption", "记录编号"),
				Map.of("Name", "WAGONNO", "DataType", "S", "Caption", "车号")
		);

		// DETAIL 表的 Rows 数据
		List<List<Object>> detailRows = new ArrayList<>();

		// 循环遍历 tblXdLjzyjlList，将数据动态添加到 detailRows 中

		// 创建新的行
		List<Object> newRow = List.of();
		// 添加行到 detailRows 中
		detailRows.add(newRow);


		// 构建 Tables 数据
		List<Map<String, Object>> tables1 = List.of(
				Map.of("Name", "BODY", "Columns", bodyColumns1, "Rows", bodyRows1),
				Map.of("Name", "DETAIL", "Columns", detailColumns, "Rows", detailRows)
		);


		String json1 = createJson(sysInfo1, tables1);
		logger.info("@@@@@@@@@@@@@@@" + json1);

//		sendJsonWithHttpClient(serverTrexConfig.getAddress(), serverTrexConfig.getPort(), serverTrexConfig.getMethod(), json1);
		/*第二次发电文*/
		long timestamp = System.currentTimeMillis();
		String timestampWithLast4Millis = timestamp + String.format("%04d", timestamp % 10000);
		// SysInfo 数据
		Map<String, Object> sysInfo = Map.of(
				"Flag", 0,
				"Msg", "",
				"SvcName", "NEM213",
				"Sender", "NE",
				"UUID", timestampWithLast4Millis
		);



		// BODY 表的 Columns 数据
		List<Map<String, String>> bodyColumns = List.of(
				Map.of("Name", "OPERATE_FLAG", "DataType", "S", "Caption", "操作标志"),
				Map.of("Name", "STATION_TRACK", "DataType", "S", "Caption", "股道代码"),
				Map.of("Name", "STATION_TRACK_CNAME", "DataType", "S", "Caption", "股道名称"),
				Map.of("Name", "USING_STATE", "DataType", "S", "Caption", "运用状态"),
				Map.of("Name", "LOCK_FLAG", "DataType", "S", "Caption", "锁定标记")
		);
		// BODY 表的 Rows 数据
		List<List<Object>> bodyRows = List.of(
				List.of("I", bodyMap.get("LINE_CODE").toString(), "", 1, 6)
		);

			logger.info("锁定标识为"+2+"需要锁线"+","+"LockLine is"+2);
		// 构建 Tables 数据
		List<Map<String, Object>> tables = List.of(
				Map.of("Name", "BODY", "Columns", bodyColumns, "Rows", bodyRows)
		);


		String json2 = createJson(sysInfo, tables);
		logger.info("@@@@@@@@@@@@@@@" + json2);

		sendJsonWithHttpClient(serverTrexConfig.getAddress(), serverTrexConfig.getPort(), serverTrexConfig.getMethod(), json2);

	}


	}

	public void receiveDataJc(String UUId, String recId, Integer wagonNum, String status,
							  String wagonNo, String DeviceNo, String wagonTypeCode,
							  String wagonTypeName, String wagonGroupCode, String stationCode,
							  String station, String areaCode, String area, String yardNoCode,
							  String yardNo, String lineCode, String line, String sendStationCode,
							  String sendStation, String arriveStationCode, String arriveStation,
							  String isNopeak, String ljzybh, Date stationTime, LocalDateTime workStartTime) {
		tblXdLjzyjlDao.recieveDataJc(UUId, recId, wagonNum, status,wagonNo, DeviceNo, wagonTypeCode,wagonTypeName, wagonGroupCode,
				stationCode,station,areaCode, area, yardNoCode,yardNo, lineCode,line, sendStationCode,sendStation, arriveStationCode,arriveStation,isNopeak,
				ljzybh,stationTime,workStartTime);
	}

	public void insertUser(String userid, String iIpAddr, LocalDateTime time) {
		tblXdLjzyjlDao.insertUser(userid, iIpAddr,time);
	}

	public String selectUserData(String remoteHost) {
		return tblXdLjzyjlDao.selectUserData(remoteHost);
	}

	public String selectJnrName(String jcrCode) {
		return tblXdLjzyjlDao.selectJnrName(jcrCode);
	}

	public List<Map<String,String>> getWagonList(String recId) {
		return tblXdLjzyjlDao.getWagonList(recId);
	}

	public List<TblXdJxchsd> getSelectById(String s) {
		return tblXdLjzyjlDao.getSelectById(s);
	}

	public List<Map<String,String >> getCarStation(String stationCode, String userCode) {
		return tblXdLjzyjlDao.getCarStation(stationCode, userCode);
	}

	public TblXdZxxdctzd selectEntity(TblXdZxxdctzd tblXdZxxdctzd) {
		String dqxlbh = tblXdZxxdctzd.getDqxlbh();
		return tblXdLjzyjlDao.selectEntity(dqxlbh);
	}
}